// PzscPage.jsx
import React, { useState, useEffect } from 'react';
import {
  Form,
  Select,
  Input,
  Button,
  Upload,
  Row,
  Col,
  Space,
  message,
  Typography,
  DatePicker, // 导入 DatePicker
} from 'antd';
import "@icon-park/react/styles/index.css";
import { UploadOutlined, FolderOpenOutlined, PlayCircleOutlined, SaveOutlined, InboxOutlined, FileExcelOutlined } from '@ant-design/icons';
import dayjs from 'dayjs'; // 导入 dayjs 用于日期处理
import backgroundImage from '../images/form_bg@2x.2d429e6ecd7d2c432e6f.png';
import PzscTable from './PzscTable';
import ApiUtils from '../utils/apiUtils';
import {request} from "../utils/requset";
import './PzscPage.css'; // 导入自定义样式
import { useNavigate } from 'react-router-dom';

const { Option } = Select;
const { Title } = Typography;
const {Dragger} = Upload;

const XmzdscPage = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [modelist, setModelist] = useState([]);
  const [xmlblist, setXmlblist] = useState([]);
  const [modeSelect, setModeSelect] = useState('');
  const [fileLoading, setFileLoading] = useState(false);
  const [loading, setLoading] = useState(false);
  const [runLoading, setRunLoading] = useState(false);
  const [filepath, setfilepath] = useState('');
  const [folderpath, setfolderpath] = useState('');
  const [error, setError] = useState(false);
  const [refreshFlag, setRefreshFlag] = useState(true)
  const [tableRefreshKey, setTableRefreshKey] = useState(0);

  useEffect(() => {
    fetchConfig();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const props = {
            name: 'file',
            multiple: true,
            directory: false,  // 禁止选择文件夹
            accept: '.xlsx,.xlsm',
            action: 'http://localhost:5000/file_upload/upload',
            onChange(info) {
                const {status, response} = info.file;
                if (status !== 'uploading') {
                    // console.log(info.file, info.fileList);
                }
                if (status === 'done') {
                    message.success(`文件 ${info.file.name} 上传成功`);
                    setTableRefreshKey(prevKey => prevKey + 1);
                    // console.log(response);
                    setRefreshFlag(!refreshFlag);
                } else if (status === 'error') {
                    if (response && response.error) {
                        message.error(`文件 ${info.file.name} 上传失败，参考错误信息：${response.error}`);
                    } else if (response) {
                        message.error(`文件 ${info.file.name} 上传失败，参考错误信息：${JSON.stringify(response)}`);
    
                    }
                }
            },
            onDrop(e){
                // 获取拖拽的文件或文件夹
                const items = e.dataTransfer.items;
                // console.log("items",items)
                for (let i = 0; i < items.length; i++) {
                  const item = items[i];
                  // console.log("item",item)
                  // console.log("kind",item.kind)
                  // console.log("type",item.type)
    
                  // 如果是文件夹，阻止上传
                  if (item.kind === 'folder' || item.type === ""||
                      item.type !== "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                      && item.type !== "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.macroEnabled.12"
                      && item.type !== "application/vnd.ms-excel.sheet.macroEnabled.12"
                  ) {
                    message.error('不支持的文件格式或文件夹');
                    e.preventDefault();  // 阻止文件夹的拖拽行为
                    return;
                  }
                }
            },
        };

  const fetchConfig = async () => {
    setLoading(true);
    try {
      const response = await request.get(ApiUtils.XMZDSC_CONFIG);
      const data = response.data;

      // 解析 modelist
      const modes = data.modelist.split(',').map((mode) => mode.trim());
      const xmlbs = data.xmlblist.split(',').map((xm) => xm.trim());
      setModelist(modes);
      setXmlblist(xmlbs);
      setfilepath(data.filepath);
      setfolderpath(data.folderpath);
      setModeSelect(data.mode);
      // 设置初始表单值
      form.setFieldsValue({
        mode: data.mode,
        xmlb: data.xmlb.split(','),
        zb: data.zb,
        nd: data.nd ? dayjs(data.nd) : null,
        basekjnd: data.basekjnd ? dayjs(data.basekjnd) : null,
        filepath: data.filepath,
        folderpath: data.folderpath, // 设置日期字段的初始值
        // 其他动态配置项可以在这里初始化
      });
    } catch (error) {
      console.error('获取配置失败:', error);
      setError('获取配置失败，请稍后再试。');
      message.error('获取配置失败，请稍后再试。');
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      const payload = {
        ...values,
        nd: values.nd.format('YYYY'),
        basekjnd: values.basekjnd.format('YYYY'),
        xmlb: values.xmlb.join(','),
      };
      setLoading(true);
      await request.post(ApiUtils.XMZDSC_UPDATE, payload);
      message.success('保存成功！');
    } catch (error) {
      if (error.response) {
        message.error(`保存失败: ${error.response.data.message}`);
      } else {
        console.error('保存配置失败:', error);
        message.error('保存配置失败，请稍后再试。');
      }
    } finally {
      setLoading(false);
    }
  };

  const handleRun = async () => {
    try {
      const values = await form.validateFields();
      const payload = {
        ...values,
        nd: values.nd.format('YYYY'),
        basekjnd: values.basekjnd.format('YYYY'),
        xmlb: values.xmlb.join(','),
      };
      setRunLoading(true);
      await request.post(ApiUtils.XMZDSC_RUN, payload);
      message.success('运行成功！');
      setTimeout(() => {
        window.location.reload();
      }, 1000);
    } catch (error) {
      if (error.response) {
        message.error(`运行失败: ${error.response.data.message}`);
      } else {
        console.error('运行配置失败:', error);
        message.error('运行配置失败，请稍后再试。');
      }
    } finally {
      setRunLoading(false);
    }
  };

  const handleModeChange = (value) => {
    // 根据选择的模式，可以动态显示或隐藏其他配置项
    // 这里可以添加更多逻辑，根据需要调整
    setModeSelect(value)
  };

  const handleFileSelect = async () => {
    setFileLoading(true);
    try {
      const response = await request.post('/select-file', {
        type: 'file',
        filetype: ['xlsx', 'xlsm', 'xls'],
        path: filepath,
      });
      const data = response.data;
      setfilepath(data.path);
      form.setFieldsValue({ filepath: data.path });
    } catch (error) {
      console.error('选择文件失败:', error);
      message.error('选择文件失败，请稍后再试。');
    } finally {
      setFileLoading(false);
    }
  };

  const handleFolderSelect = async () => {
    setFileLoading(true);
    try {
      const response = await request.post('/select-file', {
        type: 'folder',
        filetype: '',
        path: folderpath,
      });
      const data = response.data;
      setfolderpath(data.path);
      form.setFieldsValue({ folderpath: data.path });
    } catch (error) {
      console.error('选择文件夹失败:', error);
      message.error('选择文件夹失败，请稍后再试。');
    } finally {
      setFileLoading(false);
    }
  };

  const backgroundStyle = {
    backgroundImage: `url(${backgroundImage})`,
    backgroundSize: 'cover', // 使背景图片覆盖整个容器
    backgroundPosition: 'center', // 背景图片居中
    backgroundRepeat: 'no-repeat', // 防止背景图片重复
    // minHeight: '100vh', // 确保背景图片覆盖整个视口高度
    // 其他您需要的样式
  };

  return (
    <Row justify="center">
      <Col xs={24} sm={20} md={20}>
        <div className="config-page-layout float-center" style={backgroundStyle}>
          <div className="upper-section">
            <Title>
              项目字典上传
              {/* 保存和运行按钮 */}
              <Space className='float-right' style={{ marginBottom: 16, marginLeft: 8 }}>
                <Button type="default" onClick={() => navigate('/robot/test/upload')} className='float-right'>
                  <FileExcelOutlined/>Excel导入
                </Button>
                <Button type="default" onClick={handleSave} loading={loading} className='float-right'>
                  保存
                </Button>
                <Button type="primary" onClick={handleRun} loading={runLoading} className='float-right' hidden={modeSelect !== '机器人取数'}>
                  运行
                </Button>
              </Space>
            </Title>
            <Form
              form={form}
              layout="vertical"
              initialValues={{
                is_xjl: true,
              }}
            >
              <Row gutter={16}>
                {/* 模式选择 */}
                <Col xs={24} sm={12} md={8}>
                  <Form.Item
                    label="模式选择"
                    name="mode"
                    rules={[{ required: true, message: '请选择模式!' }]}
                  >
                    <Select placeholder="请选择模式" onChange={handleModeChange}>
                      {modelist.map((mode) => (
                        <Option key={mode} value={mode}>
                          {mode}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>

                <Col xs={24} sm={12} md={8} hidden={modeSelect !== '机器人取数'}>
                  <Form.Item
                    label="项目类别选择"
                    name="xmlb"
                    rules={[{ required: true, message: '请选择项目类别!' }]}
                  >
                    <Select placeholder="请选择项目类别" allowClear mode="multiple">
                      {xmlblist.map((mode) => (
                        <Option key={mode} value={mode}>
                          {mode}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>

                {/* 日期选择 */}
                <Col xs={24} sm={12} md={8} hidden={modeSelect !== '机器人取数'}>
                  <Form.Item
                    label="会计年度"
                    name="nd"
                    rules={[{ required: true, message: '请先输入会计年度!' }]}
                  >
                    <DatePicker
                      picker="year"
                      format='YYYY'
                      style={{ width: '100%' }}
                    />
                  </Form.Item>
                </Col>

                {/*/!* 账簿 *!/*/}
                {/*<Col xs={24} sm={12} md={8}>*/}
                {/*  <Form.Item*/}
                {/*    label="账簿"*/}
                {/*    name="zb"*/}
                {/*    rules={[{ required: true, message: '请先输入账簿!' }]}*/}
                {/*  >*/}
                {/*    <Input placeholder="请输入账簿" />*/}
                {/*  </Form.Item>*/}
                {/*</Col>*/}


                <Col xs={24} sm={12} md={8} hidden={modeSelect !== '手动导入'}>
                  <div className="App">
                  <Dragger {...props}>
                      <p className="ant-upload-drag-icon">
                          <InboxOutlined/>
                      </p>
                      <p className="ant-upload-text">点击或拖拽文件到此区域以上传文件</p>
                      <p className="ant-upload-hint">
                          支持上传Excel文件.xlsx和.xlsm格式; 支持多文件上传
                      </p>
                  </Dragger>
                  </div>
                </Col>
                <Col xs={24} sm={12} md={8} hidden={modeSelect !== '手动导入'}>
                  <Form.Item
                    label="会计年度"
                    name="basekjnd"
                    rules={[{ required: true, message: '请先输入会计年度!' }]}
                  >
                    <DatePicker
                      picker="year"
                      format='YYYY'
                      style={{ width: '100%' }}
                    />
                  </Form.Item>
                </Col>



              </Row>
            </Form>
          </div>

          {/* 下部分的表格 */}
          <Col>
            <div className="lower-section" hidden={modeSelect === '数据统计'} >
              <PzscTable mode={'xmzdsc'} key={tableRefreshKey} />
            </div>
          </Col>
        </div>
      </Col>
    </Row>
  );
};

export default XmzdscPage;
